package com.GlobalPaint.app.utils;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.UpdateTO;
import com.GlobalPaint.app.callback.DownloadFileCallBack;
import com.GlobalPaint.app.ui.App;
import com.blankj.utilcode.utils.EncryptUtils;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;

public class DownloadService extends IntentService {
    // 10-10 19:14:32.618: D/DownloadService(1926): 测试缓存：41234 32kb
    // 10-10 19:16:10.892: D/DownloadService(2069): 测试缓存：41170 1kb
    // 10-10 19:18:21.352: D/DownloadService(2253): 测试缓存：39899 10kb
    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private static final String TAG = "DownloadService";

    private static final int NOTIFICATION_ID = 0;
    UpdateTO updateTO;
    private NotificationManager mNotifyManager;
    private Builder mBuilder;

    public DownloadService() {
        super("DownloadService");

    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String dd="ddd";
        updateTO = new Gson().fromJson(intent.getStringExtra("updateinfo"), UpdateTO.class);
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);

        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;

        mBuilder.setContentTitle(appName).setSmallIcon(icon);
        String apkName = updateTO.getData().get(0).getUpdateurl().substring(updateTO.getData().get(0).getUpdateurl().lastIndexOf("/") + 1, updateTO.getData().get(0).getUpdateurl().length());
//        String apkUrl = getImageOSSUrl(o, apkName);
//                File apkFile = new File(dir, apkName);
        OkHttpUtils.get(updateTO.getData().get(0).getUpdateurl())//
                .tag(this)//
                .execute(new DownloadFileCallBack(Environment.getExternalStorageDirectory() + "/temp", apkName) {
                    @Override
                    public void onSuccess(final File apkFile, Call call, Response response) {
                        try {
                            installAPk(apkFile);
                          /*  // 下载完成
                            if (checkMD5(apkFile, updateTO.getData().get(0).getAppname())) {
                                installAPk(apkFile);
                            } else {
                                mBuilder.setContentText("安装包下载失败");
                                //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
                                PendingIntent pendingintent = PendingIntent.getActivity(DownloadService.this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
                                mBuilder.setContentIntent(pendingintent);
                                mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
                            }*/
                            mNotifyManager.cancel(NOTIFICATION_ID);
                        } catch (Exception e) {
                            String s = e.getMessage();
                            Log.e(this.getClass().getName(), e.getMessage());
                        }
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        System.out.println("downloadProgress -- " + totalSize + "  " + currentSize + "  " + progress + "  " + networkSpeed);
                        updateProgress((int) (progress * 100));
                    }

                    @Override
                    public void onError(Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(call, response, e);
                        String s = e.getMessage();
                        Log.e(this.getClass().getName(), e.getMessage());
                        CommUtility.ShowMsgShort(DownloadService.this, e.getMessage());
                    }
                });
    }



    private void updateProgress(int progress) {
        //"正在下载:" + progress + "%"
        mBuilder.setContentText(this.getString(R.string.android_auto_update_download_progress, progress)).setProgress(100, progress, false);
        //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
    }


    private void installAPk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
       // Intent intent = new Intent(Intent.ACTION_VIEW);
        /*//如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
        try {
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException ignored) {
        }*/



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(App.context, "com.GlobalPaint.app.fileprovider", new File(String.valueOf(apkFile)));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(String.valueOf(apkFile))), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        App.context.startActivity(intent);
    }

    private boolean checkMD5(File file, String md5) {
        String md5Value = EncryptUtils.encryptMD5File2String(file).toLowerCase();
        Log.d("md5:", md5Value);
        return md5Value.equals(md5);
    }

}
